# collaborative_dev_example.py
"""
MicroPython 协作开发指南 - 协作开发示例
MicroPython Collaborative Development Guide - Collaborative Development Example

这个文件展示了如何在团队协作中使用类型注解和标准化的开发实践
This file demonstrates how to use type annotations and standardized development practices in team collaboration
"""

from typing import Protocol, List, Dict, Optional, Union, Any, Callable
from enum import IntEnum
import time


class DeviceStatus(IntEnum):
    """设备状态枚举 | Device status enumeration"""
    INACTIVE = 0
    ACTIVE = 1
    ERROR = 2
    MAINTENANCE = 3


class SensorProtocol(Protocol):
    """
    传感器协议接口 | Sensor protocol interface
    定义了传感器必须实现的方法 | Defines methods that sensors must implement
    """
    
    def read_value(self) -> float:
        """读取传感器值 | Read sensor value"""
        ...
    
    def get_status(self) -> DeviceStatus:
        """获取设备状态 | Get device status"""
        ...
    
    def calibrate(self) -> bool:
        """校准传感器 | Calibrate sensor"""
        ...


class CollaborativeDevice:
    """
    协作开发设备类 | Collaborative development device class
    展示团队协作中的标准化类设计 | Demonstrates standardized class design in team collaboration
    """
    
    def __init__(self, 
                 device_id: int, 
                 device_name: str, 
                 device_type: str,
                 callback: Optional[Callable[[str], None]] = None) -> None:
        """
        初始化协作设备 | Initialize collaborative device
        
        参数 Parameters:
        - device_id (int): 设备ID | Device ID  
        - device_name (str): 设备名称 | Device name
        - device_type (str): 设备类型 | Device type
        - callback (Optional[Callable]): 状态变化回调 | Status change callback
        """
        self.device_id: int = device_id
        self.device_name: str = device_name
        self.device_type: str = device_type
        self.status: DeviceStatus = DeviceStatus.INACTIVE
        self.properties: Dict[str, Any] = {}
        self.history: List[Dict[str, Any]] = []
        self.callback: Optional[Callable[[str], None]] = callback
        
        self._log_event("Device initialized", {"id": device_id, "name": device_name})
    
    def _log_event(self, event: str, data: Optional[Dict[str, Any]] = None) -> None:
        """
        记录事件 | Log event
        私有方法，用于内部事件记录 | Private method for internal event logging
        """
        timestamp = time.time()
        log_entry = {
            "timestamp": timestamp,
            "event": event,
            "device_id": self.device_id,
            "data": data or {}
        }
        self.history.append(log_entry)
        
        if self.callback:
            self.callback(f"Device {self.device_id}: {event}")
    
    def activate(self) -> bool:
        """
        激活设备 | Activate device
        
        返回值 Returns:
        - bool: 激活是否成功 | Whether activation was successful
        """
        try:
            self.status = DeviceStatus.ACTIVE
            self._log_event("Device activated")
            return True
        except Exception as e:
            self.status = DeviceStatus.ERROR
            self._log_event("Activation failed", {"error": str(e)})
            return False
    
    def deactivate(self) -> bool:
        """停用设备 | Deactivate device"""
        self.status = DeviceStatus.INACTIVE
        self._log_event("Device deactivated")
        return True
    
    def set_property(self, key: str, value: Any) -> None:
        """
        设置设备属性 | Set device property
        
        参数 Parameters:
        - key (str): 属性键 | Property key
        - value (Any): 属性值 | Property value
        """
        old_value = self.properties.get(key)
        self.properties[key] = value
        self._log_event("Property updated", {
            "key": key, 
            "old_value": old_value, 
            "new_value": value
        })
    
    def get_property(self, key: str, default: Any = None) -> Any:
        """获取设备属性 | Get device property"""
        return self.properties.get(key, default)
    
    def get_device_info(self) -> Dict[str, Any]:
        """
        获取完整设备信息 | Get complete device information
        
        返回值 Returns:
        - Dict[str, Any]: 设备信息字典 | Device information dictionary
        """
        return {
            "device_id": self.device_id,
            "device_name": self.device_name,
            "device_type": self.device_type,
            "status": self.status.name,
            "properties": self.properties.copy(),
            "event_count": len(self.history),
            "last_event": self.history[-1] if self.history else None
        }
    
    def get_history(self, limit: Optional[int] = None) -> List[Dict[str, Any]]:
        """
        获取设备历史记录 | Get device history
        
        参数 Parameters:
        - limit (Optional[int]): 限制返回的记录数 | Limit number of records returned
        
        返回值 Returns:
        - List[Dict]: 历史记录列表 | History records list
        """
        if limit is None:
            return self.history.copy()
        return self.history[-limit:]


class TemperatureSensor(CollaborativeDevice):
    """
    温度传感器类 | Temperature sensor class
    继承自协作设备，实现传感器协议 | Inherits from collaborative device, implements sensor protocol
    """
    
    def __init__(self, device_id: int, device_name: str, 
                 callback: Optional[Callable[[str], None]] = None) -> None:
        super().__init__(device_id, device_name, "TemperatureSensor", callback)
        self.temperature: float = 0.0
        self.calibration_offset: float = 0.0
    
    def read_value(self) -> float:
        """
        读取温度值 | Read temperature value
        实现 SensorProtocol 接口 | Implements SensorProtocol interface
        """
        if self.status != DeviceStatus.ACTIVE:
            raise RuntimeError("Sensor is not active")
        
        # 模拟温度读取 | Simulate temperature reading
        import random
        raw_temp = 20.0 + random.uniform(-5.0, 15.0)
        calibrated_temp = raw_temp + self.calibration_offset
        
        self.temperature = calibrated_temp
        self._log_event("Temperature reading", {"temperature": calibrated_temp})
        
        return calibrated_temp
    
    def get_status(self) -> DeviceStatus:
        """获取传感器状态 | Get sensor status"""
        return self.status
    
    def calibrate(self) -> bool:
        """
        校准传感器 | Calibrate sensor
        
        返回值 Returns:
        - bool: 校准是否成功 | Whether calibration was successful
        """
        try:
            # 模拟校准过程 | Simulate calibration process
            reference_temp = 25.0  # 参考温度
            current_reading = self.read_value()
            self.calibration_offset = reference_temp - current_reading
            
            self._log_event("Sensor calibrated", {
                "reference": reference_temp,
                "reading": current_reading,
                "offset": self.calibration_offset
            })
            return True
        except Exception as e:
            self._log_event("Calibration failed", {"error": str(e)})
            return False


def device_status_logger(message: str) -> None:
    """
    设备状态记录器 | Device status logger
    用作设备状态变化的回调函数 | Used as callback for device status changes
    """
    timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
    print(f"[{timestamp}] {message}")


def demonstrate_collaborative_development() -> None:
    """
    演示协作开发模式 | Demonstrate collaborative development pattern
    
    这个函数展示了如何在团队环境中使用标准化的设备类
    This function demonstrates how to use standardized device classes in a team environment
    """
    print("协作开发示例演示 | Collaborative Development Example Demonstration")
    print("=" * 70)
    
    # 创建带有回调的温度传感器 | Create temperature sensor with callback
    temp_sensor = TemperatureSensor(
        device_id=1, 
        device_name="Room Temperature Sensor",
        callback=device_status_logger
    )
    
    print("\n1. 设备信息 | Device Information:")
    print(f"   {temp_sensor.get_device_info()}")
    
    # 激活传感器 | Activate sensor
    print("\n2. 激活传感器 | Activating Sensor:")
    activation_success = temp_sensor.activate()
    print(f"   Activation successful: {activation_success}")
    
    # 设置属性 | Set properties
    print("\n3. 设置属性 | Setting Properties:")
    temp_sensor.set_property("location", "Office Room 101")
    temp_sensor.set_property("accuracy", "±0.5°C")
    temp_sensor.set_property("range", "-10°C to 60°C")
    
    # 校准传感器 | Calibrate sensor
    print("\n4. 校准传感器 | Calibrating Sensor:")
    calibration_success = temp_sensor.calibrate()
    print(f"   Calibration successful: {calibration_success}")
    
    # 读取温度值 | Read temperature values
    print("\n5. 读取温度值 | Reading Temperature Values:")
    for i in range(3):
        try:
            temperature = temp_sensor.read_value()
            print(f"   Reading {i+1}: {temperature:.2f}°C")
        except Exception as e:
            print(f"   Error reading {i+1}: {e}")
        time.sleep(0.1)  # 短暂延迟
    
    # 显示最终设备信息 | Show final device information
    print("\n6. 最终设备信息 | Final Device Information:")
    final_info = temp_sensor.get_device_info()
    for key, value in final_info.items():
        print(f"   {key}: {value}")
    
    # 显示历史记录 | Show history
    print("\n7. 最近事件历史 | Recent Event History:")
    recent_history = temp_sensor.get_history(limit=5)
    for i, event in enumerate(recent_history, 1):
        print(f"   {i}. {event['event']} - {event.get('data', {})}")
    
    # 停用设备 | Deactivate device
    print("\n8. 停用设备 | Deactivating Device:")
    temp_sensor.deactivate()
    
    print("\n" + "=" * 70)
    print("协作开发示例完成 | Collaborative Development Example Completed")


def type_checking_guidelines() -> None:
    """
    类型检查指导原则 | Type checking guidelines
    为团队协作提供类型检查的最佳实践 | Provides type checking best practices for team collaboration
    """
    print("\n类型检查指导原则 | Type Checking Guidelines")
    print("-" * 50)
    
    guidelines = [
        "1. 所有公共函数都应该有类型注解 | All public functions should have type annotations",
        "2. 使用明确的返回类型注解 | Use explicit return type annotations",
        "3. 为复杂数据结构使用 TypedDict 或数据类 | Use TypedDict or dataclasses for complex data structures",
        "4. 使用 Protocol 定义接口契约 | Use Protocol to define interface contracts",
        "5. 合理使用 Union 和 Optional 类型 | Use Union and Optional types appropriately",
        "6. 为回调函数定义明确的 Callable 类型 | Define clear Callable types for callback functions",
        "7. 使用枚举代替魔数和字符串常量 | Use enums instead of magic numbers and string constants",
        "8. 定期运行 mypy 和 pyright 检查 | Regularly run mypy and pyright checks"
    ]
    
    for guideline in guidelines:
        print(f"   {guideline}")
    
    print(f"\n检查命令 | Checking Commands:")
    print("   mypy collaborative_dev_example.py")
    print("   pyright collaborative_dev_example.py")


if __name__ == "__main__":
    print("MicroPython 协作开发指南 - 协作开发示例")
    print("MicroPython Collaborative Development Guide - Collaborative Development Example")
    
    # 运行协作开发演示 | Run collaborative development demonstration
    demonstrate_collaborative_development()
    
    # 显示类型检查指导原则 | Show type checking guidelines
    type_checking_guidelines()
